﻿using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using mojoPortal.Business;
using System;
using System.Web;

namespace blackhouse.StareKino.Web.Navigation {
    public static class OnStartActions {

        public static void EnsureApartmentsUrl() {
            DynamicModuleUtility.RegisterModule(typeof(CoupleActionsOnModule));
        }

    }

    public class CoupleActionsOnModule : IHttpModule {

        private readonly object threadLock = new object();
        private static volatile bool _workDone;

        public void Dispose() {
        }

        public void Init(HttpApplication context) {
            context.PostAuthenticateRequest += context_PostAuthenticateRequest;

        }

        void context_PostAuthenticateRequest(object sender, EventArgs e) {
            if (!_workDone) {
                lock (this.threadLock) {
                    if (!_workDone) {
                        if (HttpContext.Current == null) return;
                        _workDone = true;
                        var siteCounts = SiteSettings.SiteCount();
                        for (var i = 1; i <= siteCounts; i++) {
                            var actionHelper = new ModuleActionsHelper(i);
                            actionHelper.Call();
                        }
                    }
                }
            }

            if (ModuleActionsHelper.RequestOnlyOnceAction()) {
                this.OnlyOnceAction();
            }

        }

        private void OnlyOnceAction() {
            var apartmentsUrl = new ApartmentsUrlEnsurance();
            apartmentsUrl.EnsureApartmentsUrl();
        }

    }


}